#!/bin/bash -e
# cgi script: article
# run without arguments displays the most recent article
# $QUERY_STRING contains either the article name, number, or number range
# denoted by: [id=]'id', name='name', range='id1'-'id2'

printf "Content-type: text/html\n\n\n"

# topmost header file
cd /srv/http/a/
cat header.htm

display_article ()
{
	# takes a file name and outputs it
	# very simple for now
	local name=$1
	shift
	local tags=$@
	if [ -z $tags ] ; then tags=$name ; fi
	printf "\n<h2>%s</h2>\n" "${tags%%;*}"
	echo "<p>"
	if [ -f $name ] ; then
		cat $name
		echo "<br /><i>${tags%;}</i>"
	else
		echo "ERROR 404"
	fi
	echo "</p>"
	echo "<hr />"
}

range_a=0
range_b=$(< latest.id)
in_range ()
{
	# return 0 if in range
	# 1 if not,
	# and 2 if there's no reason to keep trying :)
	#echo -n "$1 is: "
	if [ $1 = $range_a ] ; then
		#echo "in range"
		return 0
	elif [ $1 -lt $range_a ] ; then
		#echo "not in range"
		return 1
	elif [ $1 -le $range_b ] ; then
		#echo "in range"
		return 0
	else
		#echo "give up"
		return 2
	fi
}


table_file="table"
grep_fetch ()
{
	#results=0
	grep -i $1 $table_file | tac | while read line ; do
		split=( $line )
		filename=${split[1]}
		tags=${split[@]:2}
		display_article $filename $tags
		#results=$((results + 1))
	done
	echo "<p>End of search results for '$search'</p>"
	#echo "<p>$results Results for $search</p>"
}

id_fetch ()
{
	tac $table_file | while read line ; do
		split=( $line )
		id=${split[0]}
		filename=${split[1]}
		tags=${split[@]:2}
		in_range $id
		case $? in
		0)
			display_article $filename $tags
		;;
		1)
			continue
		;;
		*)
			break
		;;
		esac
	done
}


# if we're searching...
# TODO: sanitize this...
if [[ $QUERY_STRING == q=?* ]] ; then
	#search=$(printf "%q" ${QUERY_STRING#q=})
	search=${QUERY_STRING#q=}
	grep_fetch $search
else
	if in_range $QUERY_STRING ; then
		range_a=$QUERY_STRING
		range_b=$range_a
	fi
	id_fetch

fi

# and then print the footer and exit
cat footer.htm
